import {
  taskPageApi,
  addTaskApi,
  editTaskApi,
  delTaskApi,
  approveTaskApi,
  getDetailApi
} from '@/api/task/task'
import { Ref } from 'vue'
import { ProTableInst } from '@/components/pro-table/type'
import { PageRequest } from '@/api/types'
import { TaskModel } from '@/api/model/task-model'
import dayjs from 'dayjs'
import getUserInfo from '@/hooks/getUserInfo'

type Props = {
  handleType: Ref<'check' | 'detail' | ''>
  handleTag: Ref<string>
  taskModalShow: Ref<boolean>
  taskForm: Ref<Partial<TaskModel>>
  isInAllocate: Ref<boolean>
  isInBorrow: Ref<boolean>
  currentRow: Ref<any>
  proTableInst: Ref<ProTableInst | null>
}

export const useTaskApi = ({
  handleType,
  handleTag,
  taskModalShow,
  taskForm,
  isInAllocate,
  isInBorrow,
  currentRow,
  proTableInst
}: Props) => {
  const confirmLoading = ref(false)

  const { userInfo } = getUserInfo()
  // 获取审核列表
  const fetchTaskPage = async (
    pageRequest: PageRequest,
    queryParams: TaskModel
  ) => {
    const res = await taskPageApi({
      ...queryParams,
      orgId: userInfo.value.orgId,
      pageRequest
    })

    if (res.code === '0000') {
      return {
        data: res.data?.content,
        total: res.data?.total
      }
    }
  }

  // 新增or修改审核
  const fetchAddOrEditTask = async () => {
    confirmLoading.value = true
    const fetch = handleType.value === 'add' ? addTaskApi : editTaskApi
    const res = await fetch({
      ...taskForm.value
    })
    if (res.code === '0000') {
      useMsg('success', handleTag.value + '成功')
      proTableInst.value?.reload()
      taskModalShow.value = false
    }
    confirmLoading.value = false
  }

  // 删除审核
  const fetchDelTask = async (id) => {
    const res = await delTaskApi({ id })
    if (res.code === '0000') {
      useMsg('success', '删除成功')
      proTableInst.value?.reload()
    }
  }

  // 审批
  const fetchApproveTask = async (row, taskForm) => {
    const data = Object.assign(
      {},
      row,
      row.taskType !== '6' || row.taskType !== '3'
        ? {
            reason: taskForm.reason,
            taskStatus: taskForm.taskStatus,
            taskPerson: userInfo.value.userName,
            taskPersonId: userInfo.value.userId,
            taskDate: dayjs().format('YYYY-MM-DD')
          }
        : {}
    )

    // 领用
    if (row.taskType === '2') {
      data.assetCode = taskForm.assetCode
      data.getDate = dayjs().format('YYYY-MM-DD')
    }

    // 借用
    if (row.taskType === '3') {
      data.isInBorrow = isInBorrow.value
      if (isInBorrow.value) {
        data.taskInDate = dayjs().format('YYYY-MM-DD')
        data.taskInPerson = userInfo.value.userName
        data.taskInPersonId = userInfo.value.userId
        data.taskInStatus = taskForm.taskInStatus
        data.inReason = taskForm.inReason
      } else {
        data.taskOutDate = dayjs().format('YYYY-MM-DD')
        data.taskOutPerson = userInfo.value.userName
        data.taskOutPersonId = userInfo.value.userId
        data.taskOutStatus = taskForm.taskOutStatus
        data.outReason = taskForm.outReason
      }
    }

    // 调拨
    if (row.taskType === '6') {
      data.isInAllocate = isInAllocate.value
      if (isInAllocate.value) {
        data.taskInDate = dayjs().format('YYYY-MM-DD')
        data.taskInPerson = userInfo.value.userName
        data.taskInPersonId = userInfo.value.userId
        data.taskInStatus = taskForm.taskInStatus
        data.inReason = taskForm.inReason
      } else {
        data.taskOutDate = dayjs().format('YYYY-MM-DD')
        data.taskOutPerson = userInfo.value.userName
        data.taskOutPersonId = userInfo.value.userId
        data.taskOutStatus = taskForm.taskOutStatus
        data.outReason = taskForm.outReason
      }
    }
    if (data.__displayValue__) delete data.__displayValue__
    const res = await approveTaskApi(data)
    if (res.code === '0000') {
      useMsg('success', '审批成功')
      proTableInst.value?.reload()
    }
  }

  // 获取审核详情
  const fetchGetDetail = async (row) => {
    const res = await getDetailApi({
      code: row.receiveCode,
      type: row.taskType
    })
    if (res.code === '0000') {
      taskForm.value = Object.assign({}, res.data, currentRow.value)
      switch (row.taskType) {
        // 预算申请
        case '0':
          taskForm.value.taskStatus =
            res.data.receiveType === '0' ? null : res.data.receiveType
          break
        // 采购申请
        case '1':
          taskForm.value.taskStatus =
            res.data.purchaseStatus === '0' ? null : res.data.purchaseStatus
          break
        // 领用申请
        case '2':
          taskForm.value.taskStatus =
            res.data.receiveType === '0' ? null : res.data.receiveType
          break
        // 借用申请
        case '3':
          taskForm.value.taskInStatus =
            taskForm.value.taskInStatus === '0'
              ? null
              : taskForm.value.taskInStatus
          taskForm.value.taskOutStatus =
            taskForm.value.taskOutStatus === '0'
              ? null
              : taskForm.value.taskOutStatus
          break
        // 维修申请
        case '4':
          break
        // 报废申请
        case '5':
          taskForm.value.taskStatus =
            res.data.scrapType === '0' ? null : res.data.scrapType
          break
        // 调拨申请
        case '6':
          taskForm.value.taskInStatus =
            taskForm.value.taskInStatus === '0'
              ? null
              : taskForm.value.taskInStatus
          taskForm.value.taskOutStatus =
            taskForm.value.taskOutStatus === '0'
              ? null
              : taskForm.value.taskOutStatus
          break
        // 资产复活申请
        case '7':
          taskForm.value.taskStatus =
            res.data.easterType === '0' ? null : res.data.easterType
          break
      }
    }
  }

  return {
    fetchTaskPage,
    fetchAddOrEditTask,
    fetchDelTask,
    fetchApproveTask,
    fetchGetDetail,
    confirmLoading
  }
}
